package net.xxcl.kygl.controller;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import net.xxcl.kygl.pojo.Criteria;
import net.xxcl.kygl.pojo.Fruit;
import net.xxcl.kygl.pojo.User;
import net.xxcl.kygl.service.FruitService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * User: 夏汛
 * Date: 12-5-29
 * Time: 下午11:39
 */
@Controller
@RequestMapping("/fruit")
public class FruitController {
    @Autowired
    private FruitService fruitService;

    /**
     * 用户的成果列表
     * @param start
     * @param limit
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/listByUserId")
    public @ResponseBody Map<String,Object> listByUserId(@RequestParam(value = "start",required = false) Integer start,
                            @RequestParam(value = "limit",required = false) Integer limit,
                            HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        User user = (User)request.getSession().getAttribute("user");
        Criteria criteria = new Criteria();
        criteria.put("userid",user.getId());
        int total = fruitService.countByExample(criteria);
        if(start!=null) criteria.setMysqlOffset(start);
        if(start!=null && limit!=null) criteria.setMysqlLength(limit);
        List<Fruit> list = fruitService.selectByExample(criteria);
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 成果列表
     * @param start
     * @param limit
     * @param name
     * @param username
     * @param fruittypeid
     * @param startTime
     * @param endTime
     * @param userid
     * @return
     */
    @RequestMapping(value = "/list")
    public @ResponseBody Map<String,Object> list(@RequestParam(value = "start") Integer start,
                                                 @RequestParam(value = "limit") Integer limit,
                                                 @RequestParam(value = "name",required = false) String name,
                                                 @RequestParam(value = "username",required = false) String username,
                                                 @RequestParam(value = "fruittypeid",required = false) Integer fruittypeid,
                                                 @RequestParam(value = "startTime",required = false) String startTime,
                                                 @RequestParam(value = "endTime",required = false) String endTime,
                                                 @RequestParam(value = "userid",required = false) Integer userid){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();

        //设置查询条件
        if(!(name==null || name.equals(""))) criteria.put("blurredName","%"+name+"%");
        if(!(username==null || username.equals(""))) criteria.put("blurredUsername","%"+username+"%");
        if(!(startTime==null || startTime.equals(""))) criteria.put("startTime",startTime);
        if(!(endTime==null || endTime.equals(""))) criteria.put("endTime",endTime);
        criteria.put("fruittype",fruittypeid);
        criteria.put("userid",userid);

        //只查通过审核了的
        criteria.put("state",1);
        criteria.setOrderByClause("t_fruit.id desc");
        int total = fruitService.countByExample(criteria);
        if(start!=null) criteria.setMysqlOffset(start);
        if(start!=null && limit!=null) criteria.setMysqlLength(limit);
        List<Fruit> list = fruitService.selectByExample(criteria);
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 上报
     * @param fruit
     * @return
     */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> saveOrUpdate(@ModelAttribute("fruit") Fruit fruit,
                                                         HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String,Object>();
        User user = (User)request.getSession().getAttribute("user");
        try{
            fruit.setUserid(user.getId());
            fruitService.insertSelective(fruit);
            responseMap.put("success", "true");
            responseMap.put("info", "上报成功！");
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info", "上报失败");
        }
        return responseMap;
    }

    /**
     * 待审核成果列表
     * @param start
     * @param limit
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/listForSh")
    public @ResponseBody Map<String,Object> listForSh(@RequestParam(value = "start",required = false) Integer start,
                                                         @RequestParam(value = "limit",required = false) Integer limit,
                                                         HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        criteria.put("state",0);
        int total = fruitService.countByExample(criteria);
        if(start!=null) criteria.setMysqlOffset(start);
        if(start!=null && limit!=null) criteria.setMysqlLength(limit);
        List<Fruit> list = fruitService.selectByExample(criteria);
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 审核成果
     * @param isagree
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/submitFruitSh",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> submitFruitSh(
            @RequestParam(value = "isagree") Boolean isagree,@RequestParam(value = "id") Integer id,
            HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        try{
            Fruit fruit = new Fruit();
            fruit.setId(id);
            if(isagree){
                //审核通过
                fruit.setState(1);
                fruitService.updateByPrimaryKeySelective(fruit);
            } else {
                //审核不通过
                fruitService.deleteByPrimaryKey(id);
            }
            responseMap.put("success", "true");
            if(isagree){
                responseMap.put("info", "审核通过");
            } else {
                responseMap.put("info", "审核不通过，删除该成果");
            }
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","成果状态改变失败");
        }
        return responseMap;
    }

    @RequestMapping(value="/import",method=RequestMethod.POST)
    public void importFromExcel(MultipartHttpServletRequest request,HttpServletResponse response){
        MultipartFile file = request.getFile("file");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            if(!file.isEmpty()){
                String fileHz = "";
                //如果文件类型是excel 2003，后缀名设置为.xls，excel 2007则设置为.xlsx
                if(file.getContentType().equals("application/vnd.ms-excel")){
                    fileHz = ".xls";
                } else {
                    out.print("{'info':'暂只能支持excel 2003格式的文件'}");
                    return;
                }

                String filePath = request.getSession().getServletContext().getRealPath("/");
                String fileName = UUID.randomUUID() + fileHz;

                File dirPath = new File(filePath);
                if (!dirPath.exists()) {
                    dirPath.mkdirs();
                }
                String realPath = filePath+File.separator+"temp"+File.separator+fileName;
                File saveFile = new File(realPath);
                FileUtils.writeByteArrayToFile(saveFile, file.getBytes());
                out.print("{'info':'"+importToDB(realPath)+"'}");
            }
        } catch(Exception e) {
            e.printStackTrace();
            out.print("{'info':'导入失败！'");
        } finally {
            if(out!=null){
                out.flush();
                out.close();
            }
        }
        return;
    }

    private String importToDB(String fileToBeRead){
        String message = "";    //返回的信息
        int totalSuccess = 0;   //导入成功条数
        int total = 0;          //总条数
        String errorLine = "";  //错误的行号
        try{
            //创建对工作薄的引用
            Workbook book = Workbook.getWorkbook(new File(fileToBeRead));
            //创建对第一张工作表的引用
            Sheet sheet = book.getSheet(0);
            //获取有效行数（可能中间有空行，因此不等于总条数）
            int rowNumber = sheet.getRows();
            //i=1开始循环，默认第一行为标题行，不读取
            for(int i=1;i<rowNumber;i++){
                //获取行数据
                Cell[] cells = sheet.getRow(i);
                //第二列为设置的必选，如果该列没有内容，那么认为该行是空行
                if(cells[1].getContents()==null || cells[1].getContents().equals("")){
                    continue;
                }
                total += 1;
                try{
                    fruitService.saveExcelRow(cells);
                    totalSuccess += 1;
                } catch (RuntimeException e){
                    message += "第"+(total+1)+"行导入失败，原因：<br />" + e.getMessage() + "<br />";
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        message = "导入成功"+totalSuccess+"条记录！<br />" + message;
        return message;
    }
}
